from django.urls import resolve
from rest_framework.response import Response
import json


class UserStatusMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        # print('request: ', request)
        # print('get_full_path: ', request.get_full_path())
        # print('get_raw_uri: ', request.get_raw_uri())
        # print('url name: ', resolve(request.path_info).url_name)

        # Code to be executed for each request/response after
        # the view is called.
        # try:
        #   print(request.META['HTTP_COOKIE'])
        # except Exception as e:
        #   print(str(e))
        response = self.get_response(request)
        if request.user.is_authenticated and request.user.user_status != 'N' or request.user.is_authenticated == False:
            print(f"========账号已过期或账号密码有误=========")
            response.delete_cookie(key='USER_TYPE')
            response.delete_cookie('USER_NAME')
            response.delete_cookie('USER_EMAIL')
            response.delete_cookie('USER_REAL_NAME')
            response.delete_cookie('USER_PHONE')
            response.delete_cookie('vlab_session_id')
            response.delete_cookie('sessionid')

        # response = self.get_response(request)

        # if resolve(request.path_info).url_name in ['experimenting', 'buyExperiment', 'buyExam', 'report', 'examing', 'studying', 'buyCourse']:
        #   try:
        #     student = self.request.user.student
        #   except Exception as e:
        #     return Response({
        #       'error_msg': '请登录学生账号进行操作',
        #       'error_code': -1000
        #     }, template_name='403.html')
        return response
